package club.yuit.desktop.ui.consumer;

import club.yuit.desktop.editor.LogEditorPane;
import club.yuit.desktop.model.ConsumerContext;
import club.yuit.desktop.ui.UITools;
import club.yuit.rmq.service.ConsumerService;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.consumer.FilterExpression;
import org.apache.rocketmq.client.apis.consumer.MessageListener;
import org.apache.rocketmq.client.apis.consumer.PushConsumer;
import org.apache.rocketmq.client.apis.message.MessageView;

import javax.annotation.processing.FilerException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;

import static club.yuit.desktop.ui.UIConstants.DEFAULT_SIZE;

/**
 * @author: yuit
 * @date: 2023/12/12 13:23
 */
public class ConsumerUI extends JFrame {

    private final ConsumerContext context;
    private final LogEditorPane logEditorPane;

    private final Object lock = new Object();


    public ConsumerUI(ConsumerContext context, Component relativeTo) throws HeadlessException {
        this.context = context;
        this.setTitle("Consumer:[" + context.getTopic() + "]");
        this.setLocationRelativeTo(relativeTo);
        this.setSize(DEFAULT_SIZE);
        logEditorPane = new LogEditorPane();
        ImageIcon icon = UITools.getSVGIcon("/imgs/Icon.svg",16,16);
        this.setIconImage(icon.getImage());
        logEditorPane.setEditable(false);
        this.getContentPane().setLayout(new BorderLayout());
        JScrollPane sc = new JScrollPane(logEditorPane);
        sc.setBorder(null);
        this.getContentPane().add(sc, BorderLayout.CENTER);
        startConsumer();
    }

    public void startConsumer() {
        ConsumerService consumerService = context.getConsumerService();

        Map<String, FilterExpression> mp = Collections.singletonMap(context.getTopic(), context.getFilterExpression());
        PushConsumer consumer = consumerService.pushConsumer(
                context.getMessageGroup(),
                mp,
                mv -> {
                    synchronized (lock) {
                        logEditorPane.insertValue("[SUCCESS]\n", Color.GREEN);

                        StringBuilder vb = new StringBuilder();
                        String id = mv.getMessageId().toString();
                        vb.append("ID:")
                                .append(id);

                        // 读取转换消息体
                        ByteBuffer body = mv.getBody();
                        byte[] bts = new byte[body.remaining()];
                        body.get(bts);
                        // 也可直接转换为JSON
                        String bodyValue = new String(bts);

                        mv.getMessageGroup().ifPresent(v -> {
                            vb.append("\nMessageGroup:")
                                    .append(v);
                        });
                        String bornHost = mv.getBornHost();
                        vb.append("\nBornHost:")
                               .append(bornHost);
                        Collection<String> keys = mv.getKeys();
                        vb.append("\nKeys:\n")
                                .append(String.join(",", keys));

                        mv.getDeliveryTimestamp().ifPresent(v -> {
                            vb.append("\nDeliveryTimestamp:")
                                    .append(v);
                        });
                        mv.getTag().ifPresent(v -> {
                            vb.append("\nTAG:")
                                    .append(v);
                        });

                        Map<String, String> properties = mv.getProperties();
                        vb.append("\nProperties:\n");
                        properties.forEach((k,v)->{
                            vb.append(k)
                                    .append("=")
                                   .append(v)
                                   .append("\n");
                        });

                        vb.append("Body:\n")
                                        .append(bodyValue)
                                .append("\n");

                        logEditorPane.insertValue(vb.toString(),Color.BLACK);
                    }


                    return ConsumeResult.SUCCESS;
                }
        );


        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                if (consumer != null) {
                    try {
                        consumer.close();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }

            }
        });

    }


}
